package org.edu.modules.kwgl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.system.query.QueryGenerator;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.oConvertUtils;
import org.edu.modules.kwgl.entity.VeJwCjyj;
import org.edu.modules.kwgl.entity.VeJwCjyjExcel;
import org.edu.modules.kwgl.service.IVeJwCjyjService;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @Description: 学生预警信息
 * @Author: jeecg-boot
 * @Date: 2024-01-01
 * @Version: V1.0
 */
@Api(tags = "学生预警信息")
@RestController
@RequestMapping("/kwgl/veJwCjyj")
@Slf4j
public class VeJwCjyjController extends BaseController<VeJwCjyj, IVeJwCjyjService> {
    @Autowired
    private IVeJwCjyjService veJwCjyjService;

    /**
     * 分页列表查询
     *
     * @param veJwCjyj
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "学生预警信息-分页列表查询")
    @ApiOperation(value = "学生预警信息-分页列表查询", notes = "学生预警信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(VeJwCjyj veJwCjyj,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isEmpty(loginUser)) {
            return Result.error("请登录系统！");
        }
        QueryWrapper<VeJwCjyj> queryWrapper = QueryGenerator.initQueryWrapper(veJwCjyj, req.getParameterMap());
        queryWrapper.orderByDesc("create_time");
        Page<VeJwCjyj> page = new Page<VeJwCjyj>(pageNo, pageSize);
        IPage<VeJwCjyj> pageList = veJwCjyjService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param veJwCjyj
     * @return
     */
    @AutoLog(value = "学生预警信息-添加")
    @ApiOperation(value = "学生预警信息-添加", notes = "学生预警信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody VeJwCjyj veJwCjyj) {
        //同一个学生 同一个类型只能有一个
        QueryWrapper<VeJwCjyj> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("xh", veJwCjyj.getXh());
        queryWrapper.eq("warning_reason", veJwCjyj.getWarningReason());
        List<VeJwCjyj> list = veJwCjyjService.list(queryWrapper);
        if (list.size() > 0) {
            return Result.error("该学生已经存在"+(veJwCjyj.getWarningReason()==1?"学分预警":"不及格门数预警")+"信息！");
        }
        veJwCjyjService.save(veJwCjyj);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param veJwCjyj
     * @return
     */
    @AutoLog(value = "学生预警信息-编辑")
    @ApiOperation(value = "学生预警信息-编辑", notes = "学生预警信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody VeJwCjyj veJwCjyj) {
        veJwCjyjService.updateById(veJwCjyj);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "学生预警信息-通过id删除")
    @ApiOperation(value = "学生预警信息-通过id删除", notes = "学生预警信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        veJwCjyjService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "学生预警信息-批量删除")
    @ApiOperation(value = "学生预警信息-批量删除", notes = "学生预警信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.veJwCjyjService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "学生预警信息-通过id查询")
    @ApiOperation(value = "学生预警信息-通过id查询", notes = "学生预警信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        VeJwCjyj veJwCjyj = veJwCjyjService.getById(id);
        if (veJwCjyj == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(veJwCjyj);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param veJwCjyj
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, VeJwCjyj veJwCjyj) {
        return super.exportXls(request, veJwCjyj, VeJwCjyj.class, "学生预警信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, VeJwCjyj.class);
    }

    /**
     * 自定义导出excel
     *
     * @param request
     * @param veJwCjyj
     */
    @RequestMapping(value = "/exportXlsCustom")
    public ModelAndView exportXlsCustom(HttpServletRequest request, VeJwCjyj veJwCjyj) {
        // 查询数据
        QueryWrapper<VeJwCjyj> queryWrapper = QueryGenerator.initQueryWrapper(veJwCjyj, request.getParameterMap());
        queryWrapper.orderByDesc("createTime");
        List<VeJwCjyj> list = veJwCjyjService.list(queryWrapper);

        // 转换为Excel实体
        List<VeJwCjyjExcel> excelList = new ArrayList<>();
        for (VeJwCjyj item : list) {
            VeJwCjyjExcel excelItem = new VeJwCjyjExcel();
            excelItem.setXh(item.getXh());
            excelItem.setXm(item.getXm());
            excelItem.setZy(item.getZy());
            excelItem.setBj(item.getBj());
            // 预警原因转换
            if (item.getWarningReason() != null) {
                if (item.getWarningReason() == 1) {
                    excelItem.setWarningReasonName("学分预警");
                } else if (item.getWarningReason() == 2) {
                    excelItem.setWarningReasonName("不及格门数预警");
                }
            }
            // 预警等级转换
            if (item.getWarningLevel() != null) {
                if (item.getWarningLevel() == 1) {
                    excelItem.setWarningLevelName("高");
                } else if (item.getWarningLevel() == 2) {
                    excelItem.setWarningLevelName("中");
                } else if (item.getWarningLevel() == 3) {
                    excelItem.setWarningLevelName("低");
                }
            }
            excelItem.setRectificationRequirements(item.getRectificationRequirements());
            excelItem.setContactPerson(item.getContactPerson());
            excelItem.setContactInfo(item.getContactInfo());
            excelList.add(excelItem);
        }

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject("fileName", "学生预警信息");
        mv.addObject("entity", VeJwCjyjExcel.class);
        mv.addObject("params", new ExportParams("学生预警信息报表", "导出人:" + sysUser.getRealname(), "学生预警信息"));
        mv.addObject("data", excelList);
        return mv;
    }

    /**
     * 通过excel导入数据（自定义）
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcelCustom", method = RequestMethod.POST)
    public Result<?> importExcelCustom(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Iterator var6 = fileMap.entrySet().iterator();
        if (var6.hasNext()) {
            Map.Entry<String, MultipartFile> entity = (Map.Entry) var6.next();
            MultipartFile file = (MultipartFile) entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            params.setHeadRows(1);
            params.setNeedSave(true);

            Result var11;
            try {
                List<VeJwCjyjExcel> list = org.jeecgframework.poi.excel.ExcelImportUtil.importExcel(file.getInputStream(), VeJwCjyjExcel.class, params);
                long start = System.currentTimeMillis();
                List<VeJwCjyj> targetList = new ArrayList<>();
                int success = 0;
                int error = 0;
                for (VeJwCjyjExcel item : list) {
                    VeJwCjyj veJwCjyj = new VeJwCjyj();
                    veJwCjyj.setXh(item.getXh());
                    veJwCjyj.setXm(item.getXm());
                    veJwCjyj.setZy(item.getZy());
                    veJwCjyj.setBj(item.getBj());
                    // 预警原因转换
                    if ("学分预警".equals(item.getWarningReasonName())) {
                        veJwCjyj.setWarningReason(1);
                    } else if ("不及格门数预警".equals(item.getWarningReasonName())) {
                        veJwCjyj.setWarningReason(2);
                    }
                    // 预警等级转换
                    if ("高".equals(item.getWarningLevelName())) {
                        veJwCjyj.setWarningLevel(1);
                    } else if ("中".equals(item.getWarningLevelName())) {
                        veJwCjyj.setWarningLevel(2);
                    } else if ("低".equals(item.getWarningLevelName())) {
                        veJwCjyj.setWarningLevel(3);
                    }
                    veJwCjyj.setRectificationRequirements(item.getRectificationRequirements());
                    veJwCjyj.setContactPerson(item.getContactPerson());
                    veJwCjyj.setContactInfo(item.getContactInfo());
                    veJwCjyj.setCreateTime(new Date());
                    targetList.add(veJwCjyj);
                    success++;
                }
                this.veJwCjyjService.saveOrUpdateBatch(targetList);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                if (error == 0) {
                    return Result.ok("文件导入成功！数据行数：" + targetList.size());
                } else {
                    return Result.ok("文件导入成功！成功" + success + "条，失败" + error + "条");
                }
            } catch (Exception var23) {
                log.error(var23.getMessage(), var23);
                var11 = Result.error("文件导入失败:" + var23.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException var22) {
                    var22.printStackTrace();
                }
            }
            return var11;
        } else {
            return Result.error("文件导入失败！");
        }
    }
} 